//
//  HealthRecordViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/9.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "HealthRecordViewController.h"
#import "ZRecordTableViewCell.h"
#import "ZNewBuiltViewController.h"
#import "ZHealthDetailedViewController.h"
#import "ZHealthModel.h"
#import "SPPlaceholderCell.h"
static NSString *const placeCellID = @"placeholders";

static NSString * const KZRecordIdentifier = @"KZRecordIdentifier";
@interface HealthRecordViewController ()<UITableViewDelegate,UITableViewDataSource,ZNewBuiltViewControllerDelegate> {
    LZUserInfo *userInfo;
}
@property (nonatomic,strong) UITableView * mainTableView;
/** 健康档案模型数组 */
@property (nonatomic, strong) NSMutableArray <ZHealthModel *>*dataArray;
@property (nonatomic,assign) BOOL isHaveData;
@end

@implementation HealthRecordViewController

// 移除观察者
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_mainTableView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    // 登录发送通知，改变界面.添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(LUserInfoLogin) name:@"LLoginSuccess" object:nil];
    
    [self initialzeDatas];
    [self initlizeInterface];
    
}

// 接受通知以后做的事情
- (void)LUserInfoLogin {
    [self pullDownData];
}

- (void)initialzeDatas {
    userInfo = [LZUserInfo getUserInfo];
    _dataArray = [NSMutableArray array];
    self.isHaveData = YES;
}
- (void)initlizeInterface {
    UIButton * rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 30, 30);
    [rightButton setImage:[UIImage imageNamed:@"icon_nav_add"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(newBuiltRecord) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightltem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightltem;
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.mainTableView];
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.width.left.equalTo(self.view);
//        make.height.equalTo(self.view).offset(-44);
        make.edges.equalTo(self.view);
    }];
    
    __weak typeof(self) weakSelf = self;
    // 下拉刷新
    self.mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf pullDownData];
        [weakSelf.mainTableView.mj_header endRefreshing];
    }];
    // 上拉加载
//    self.mainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        [weakSelf pullUpData];
//        [weakSelf .mainTableView.mj_footer endRefreshing];
//    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 点击新建
- (void)newBuiltRecord {
    ZNewBuiltViewController * ZNBVC = [[ZNewBuiltViewController alloc] init];
    ZNBVC.delegate = self;
    [self.navigationController pushViewController:ZNBVC animated:YES];
}

- (void)HealthNetWorking {
    
}
//表格视图协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.isHaveData? self.dataArray.count : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == YES) {
        ZRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:KZRecordIdentifier forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.heathModel = _dataArray[indexPath.row];
    
        return  cell;
    }else {
        SPPlaceholderCell *cell = [tableView dequeueReusableCellWithIdentifier:placeCellID];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == YES) {
        return 95*ysIZE;
    }else {
        return  SCREEN_Height-104;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isHaveData == NO) {
        return;
    }
    NSString * fileID = _dataArray[indexPath.row].fileID;
    if (!fileID || [fileID isEqualToString:@""]) {
        [YJProgressHUD showMessage:@"没有网络" inView:self.view];
        return;
    }
    ZHealthDetailedViewController * ZHDVC = [[ZHealthDetailedViewController alloc]init];
    // 档案id传到下个界面
    ZHDVC.fileID = fileID;
    ZHDVC.navigationItem.title = _dataArray[indexPath.row].title;
    [self.navigationController pushViewController:ZHDVC animated:YES];
}


- (UITableView *)mainTableView {
    if (_mainTableView) {
        return _mainTableView;
    }
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _mainTableView.dataSource = self;
    _mainTableView.delegate = self;
//    _mainTableView.rowHeight = 95*ysIZE;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mainTableView.backgroundColor = MYGRAYCOLOR;
    [_mainTableView registerClass:[ZRecordTableViewCell class] forCellReuseIdentifier:KZRecordIdentifier];
    [_mainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([SPPlaceholderCell class]) bundle:nil] forCellReuseIdentifier:placeCellID];
    return _mainTableView;
}

// 下拉刷新方法
- (void)pullDownData {
    __weak typeof(self) weakSelf = self;
    NSDictionary *paramas = @{@"uid":userInfo.uid};
    self.isHaveData = YES;
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/index" sucessBlock:^(id content) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        LZLog(@"-------健康档案首页数据------%@",dict);
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"刷新成功" inView:self.view];
            [weakSelf dealPullDownDataWithDict:dict];
        }else if ([dict[@"code"] intValue] == 0) {
            self.isHaveData = NO;
            [self.mainTableView reloadData];
            [YJProgressHUD showMessage:@"加载失败" inView:self.view];
        }
    } failure:^(NSError *error) {
        self.isHaveData = NO;
        [self.mainTableView reloadData];
        [YJProgressHUD showMessage:@"请求失败" inView:self.view];
    }];
    
}
// 上拉加载方法
- (void)pullUpData {
    
}


// 处理下拉刷新以后的数据
- (void)dealPullDownDataWithDict:(NSDictionary *)dict {
    [_dataArray removeAllObjects];
    NSArray *tempArr = dict[@"list"];
    if (tempArr.count == 0) {
        self.isHaveData = NO;
    }
    for (NSDictionary *dict in tempArr) {
        ZHealthModel *healthModel = [[ZHealthModel alloc] initWithDict:[dict mutableCopy]];
        [_dataArray addObject:healthModel];
    }
    [_mainTableView reloadData];
}

// 下个界面返回以后刷新这个界面
- (void)refreshUI {
    [self pullDownData];
}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSDictionary *paramas = @{@"id":_dataArray[indexPath.row].fileID};
        [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:paramas paramarsSite:@"File/delFile" sucessBlock:^(id content) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
            LZLog(@"-----删除健康档案数据-----%@",dict);
            if ([dict[@"code"] intValue] == 1) {
                [YJProgressHUD showMessage:@"删除成功" inView:self.view];
            }else {
                [YJProgressHUD showMessage:@"删除失败" inView:self.view];
            }
        } failure:^(NSError *error) {
            LZLog(@"%@",error);
        }];
        [_dataArray removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [_mainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}


@end
